import datetime
import os
import re
import shutil
import time


def findCoupon(basepath, date):
    h = datetime.datetime.today().strftime("%Y%m%d")

    # 不存在Data文件，先创建文件
    if not os.path.exists(f"{h}.txt"):
        with open(f"{h}.txt", "w", encoding='utf-8') as w1:
            pass
        w1.close()

    # 读取历史优惠券ID
    with open(f"{h}.txt", "r", encoding='utf-8') as r1:
        line1 = r1.read()
        print(line1)
    r1.close()

    #遍历所有文件
    for index, (root, dir, files) in enumerate(os.walk(basepath)):
        # 过滤目录
        if date not in root:
            continue
        for file in files:
            # 过滤文件夹
            if file[-3:] == 'zip':
                continue
            with open(fr'{root}\{file}', "r", encoding='utf-8') as f:
                line = f.read()
                # 过滤文件内容
                if "<COUPON>" in line and "<szTaType>SA</szTaType>" in line:
                    # 过滤文件内容
                    if "<bIsLoyaltyECoupon>1</bIsLoyaltyECoupon>" in line:
                        continue
                    lRetailStoreID = re.findall(r'<lRetailStoreID>(.*)</lRetailStoreID>', line)[0]
                    lWorkstationNmbr = re.findall(r'<lTaCreatedWorkstationNmbr>(.*)</lTaCreatedWorkstationNmbr>', line)[0]
                    SequenceNumber = re.findall(r'<lTaCreatedTaNmbr>(.*)</lTaCreatedTaNmbr>', line)[0]
                    szTaCreatedDate = re.findall(r'<szTaCreatedDate>(.*)</szTaCreatedDate>', line)[0][:8]
                    ScanCode = re.findall(r'<szScanCode>(.*)</szScanCode>', line)[0]
                    # 过滤文件内容
                    if ScanCode in line1:
                        continue
                    # 临时文件写入数据
                    with open("data.txt", "a", encoding='utf-8') as f1:
                        print('{"couponCode":"'+ ScanCode + '","orderCode":"'+ lRetailStoreID + lWorkstationNmbr + SequenceNumber + szTaCreatedDate + '"}' + "\n")
                        f1.write('{"couponCode":"'+ ScanCode + '","orderCode":"'+ lRetailStoreID + lWorkstationNmbr + SequenceNumber + szTaCreatedDate + '"}' + "\n")
                    f1.close()
                    # 历史文件写入数据
                    with open(f"{h}.txt", "a", encoding='utf-8') as f2:
                        f2.write('{"couponCode":"'+ ScanCode + '","orderCode":"'+ lRetailStoreID + lWorkstationNmbr + SequenceNumber + szTaCreatedDate + '"}' + "\n")
                    f2.close()
            f.close()
    # 复制生成的数据到指定目录，暂停秒数后，执行核销程序。
    shutil.copyfile("data.txt", r'E:\Wincor\Coupon\exe\data.txt')
    time.sleep(3)
    os.startfile(r"E:\Wincor\Coupon\exe\ManualUseCoupon.exe") #运行指定程序
    # 清空临时文件数据
    with open("data.txt", "w", encoding='utf-8') as f3:
        f3.write("")
    f3.close()


def task(basepath, date):
    index = 0
    hour = int(datetime.datetime.today().strftime("%H"))
    while True:
        if hour > index:
            findCoupon(basepath, date)
            index = hour
        else:
            hour = int(datetime.datetime.today().strftime("%H"))
            if hour == 0:
                index = 0
        time.sleep(2)
        print(hour, index)


if __name__ == '__main__':
    # basepath = r'D:\Disktop\新建文件夹 (11)'
    # date = '202201'
    basepath = input(r'')
    date = input(r'')

    # findCoupon(basepath, date)

    task(basepath, date)